package com.xjh.serverinspect.security.handler;

import com.alibaba.fastjson2.JSON;
import com.xjh.serverinspect.security.CaptchaException;
import com.xjh.serverinspect.security.ResponseBodyHandler;
import com.xjh.serverinspect.util.ResponseCodeEnum;
import com.xjh.serverinspect.util.ResponseDTO;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 登录失败处理器
 * </p>
 *
 * @author xujinghui
 * @since 2024-12-12
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = resp.getOutputStream();

        ResponseDTO result;
        if (e instanceof CaptchaException) {
            result = ResponseDTO.error(ResponseCodeEnum.CAPTCHA_ERROR);
        } else {
            result = ResponseDTO.error(ResponseCodeEnum.USERNAME_OR_PASSWORD_ERROR);
        }
        outputStream.write(JSON.toJSONBytes(ResponseBodyHandler.encrypt(result, req)));
        outputStream.flush();
        outputStream.close();
    }
}
